package 极客时间.concurrence.并发编程实战篇.信号量模型;

import lombok.SneakyThrows;
import 极客时间.concurrence.并发编程理论基础.面向对象写多线程.Counter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * @Author idea
 * @Date created in 8:28 上午 2020/7/24
 */
public class SemaphoreDemo {

    private static int count;
    private static final Semaphore semaphore = new Semaphore(1);

    /**
     * 感觉加入了 semaphore 也可以用于做一把锁限制每次进入的线程数目
     */
    private static void incr(){
        try {
            semaphore.acquire();
            count=count+1;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            semaphore.release();
        }
    }

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 1000; i++) {
            Thread t = new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    incr();
                    System.out.println(count);
                }
            });
            t.start();
        }
        countDownLatch.countDown();
        Thread.yield();
    }
}
